package com.gensdai.leliang.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gensdai.leliang.R;
import com.gensdai.leliang.base.BaseActivityNoAbs;
import com.gensdai.leliang.dialog.Upload;
import com.gensdai.leliang.json_base.json_base;
import com.gensdai.leliang.remoteInterface.ApiService;
import com.gensdai.leliang.utils.BaseUtils;
import com.trello.rxlifecycle2.android.ActivityEvent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/5/26.
 */

public class quick_login extends BaseActivityNoAbs {
    @BindView(R.id.login_phone)
    EditText login_phone;
    @BindView(R.id.one_mm)
    EditText one_mm;
    @BindView(R.id.two_mm)
    EditText two_mm;
    @BindView(R.id.invite_code)
    EditText invite_code;
    @BindView(R.id.next_wave)
    TextView next_wave;
    @BindView(R.id.ui_title)
    TextView ui_title;
    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.protocol)
    TextView protocol; //注册协议

    private Upload up;
    private int time = 30;// 间隔时间
    private final int NOTE = 1;// 短信标识
    private final int NEXT = 2;// 下一步触发间隔
    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case NOTE:
                    up.dismiss();
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {
                            Intent go_queick_two = new Intent(quick_login.this, quick_login_two.class);
                            go_queick_two.putExtra("phone", login_phone.getText().toString().trim());
                            go_queick_two.putExtra("mm", one_mm.getText().toString().trim());
                            go_queick_two.putExtra("invite_code", invite_code.getText().toString().trim());
//                            go_queick_two.putExtra("invite_code", "2828");
                            startActivity(go_queick_two);
                            quick_login.this.finish();
                        } else {

                        }
                        Toast.makeText(
                                quick_login.this,
                                new JSONObject((String) msg.obj)
                                        .getString("message"),
                                Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case NEXT:
                    if (time > 0) {
                        next_wave.setText(time + "s");
                        time--;
                        handler.sendEmptyMessageDelayed(NEXT,1000);
                    } else {
                        time = 30;
                        next_wave.setText("下一步");
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.quick_login);
        ButterKnife.bind(this);
        init();
        setonclick();
    }


    /**
     * 初始化
     */
    private void init() {
        ui_title.setText(getResources().getString(R.string.quick_login));
        up = new Upload(this);
    }


    /**
     * 设置点击事件
     */
    private void setonclick() {
        next_wave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(one_mm.getText().toString().trim())) {
                    Toast.makeText(quick_login.this, getResources().getString(R.string.error_mm_null), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(invite_code.getText().toString().trim())) {
                    Toast.makeText(quick_login.this, getResources().getString(R.string.invite_code_null), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (one_mm.getText().toString().trim().length() < 6) {
                    Toast.makeText(quick_login.this, "密码不能小于6位！~", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!one_mm.getText().toString().trim().equals(two_mm.getText().toString().trim())) {
                    Toast.makeText(quick_login.this, getResources().getString(R.string.error_mm), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (login_phone.getText().toString().trim().length() != 11) {
                    Toast.makeText(quick_login.this, "请输入正确手机号！~", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(next_wave.getText().toString().trim().equals("下一步")) {
                    RegisterRequest2Str();
                    handler.sendEmptyMessage(NEXT);
                }

            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                quick_login.this.finish();
            }
        });
        protocol.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent go_loog_logindeal = new Intent(quick_login.this, LoginDeal.class);
                go_loog_logindeal.putExtra("title","乐粮注册协议");
                go_loog_logindeal.putExtra("type","2");
                quick_login.this.startActivity(go_loog_logindeal);
            }
        });
    }

    /**
     * 调用发短信接口
     */
    private void RegisterRequest2Str() {
        //获取edit的值后请求
        Log.e("........", "处理点击事件");
        String name = login_phone.getText().toString().trim();
        String password = one_mm.getText().toString().trim();
        if (TextUtils.isEmpty(password)) {
            return;
        }

        String resultPassword = BaseUtils.EncryptedPassword(password);
        Log.d("password", resultPassword);

        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("phone", /*"123456"*/name);   //手机号
        loginParams.put("password", resultPassword);                  //密码
//        loginParams.put("inviteCode", "2828");                //邀请码
        loginParams.put("inviteCode", invite_code.getText().toString().trim());                //邀请码
        loginParams.put("inputCode", "");                 //输入的验证码
        loginParams.put("isNext", "true");                 //是下一步
        toStr(loginParams);
    }

    //返回字符串类型
    private void toStr(Map<String, String> loginParams) {
        up.show();
        ApiService.getInstance(this).Register2Str(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = NOTE;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        up.dismiss();
                        Toast.makeText(quick_login.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }
}
